package com.ruoyi.workflow.service.impl;

import com.ruoyi.common.constant.HttpStatus;
import com.ruoyi.common.core.page.PageDomain;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.core.page.TableSupport;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.bean.BeanUtils;
import com.ruoyi.workflow.domain.CarPackageAudit;
import com.ruoyi.workflow.service.IBpmnNodeService;
import com.ruoyi.workflow.service.ICarPackageAuditService;
import com.ruoyi.workflow.service.IDoneTaskService;
import com.ruoyi.workflow.vo.CarPackageAuditVO;
import com.ruoyi.workflow.vo.HistoricActivity;
import org.activiti.engine.HistoryService;
import org.activiti.engine.RuntimeService;
import org.activiti.engine.TaskService;
import org.activiti.engine.history.HistoricActivityInstance;
import org.activiti.engine.history.HistoricProcessInstance;
import org.activiti.engine.history.HistoricTaskInstance;
import org.activiti.engine.task.Comment;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

@Service
    public class DoneTaskServiceImpl implements IDoneTaskService {

    @Autowired
    private TaskService taskService;

    @Autowired
    private RuntimeService runtimeService;

    @Autowired
    private ICarPackageAuditService carPackageAuditService;

    @Autowired
    private IBpmnNodeService bpmnNodeService;

    @Autowired
    private HistoryService historyService;

    @Override
    public TableDataInfo selectDoneList(CarPackageAudit carPackageAudit) {
        //1. 接收前端的分页参数
        TableDataInfo tableDataInfo = new TableDataInfo();
        tableDataInfo.setCode(HttpStatus.SUCCESS);
        // 2. 以当前用户作为负责人, 统计任务个数
        String username = SecurityUtils.getUsername();
        long totol = historyService.createHistoricTaskInstanceQuery()
                .taskAssignee(username)
                .finished()
                .count();
        // 3. 如果数量为 0, 返回空数据.
        tableDataInfo.setTotal(totol);
        if (totol == 0){
            tableDataInfo.setRows(Collections.emptyList());
            return tableDataInfo;
        }
        // 4. 如果有数据, 构建分页条件
        PageDomain pageDomain = TableSupport.buildPageRequest();
       int srarIndex= (pageDomain.getPageNum() - 1) * pageDomain.getPageSize();
        // 5. 以当前用户作为负责人, 查询所有已经完成的任务列表
        List<HistoricTaskInstance> taskInstanceList = historyService.createHistoricTaskInstanceQuery()
                .taskAssignee(username)
                .finished()
                .orderByTaskCreateTime()
                .asc()
                .listPage(srarIndex, pageDomain.getPageSize());
        // 6. 创建一个集合, 用于存储最终返回的数据列表
        List<CarPackageAudit> list = new ArrayList<>();
        // 7. 遍历任务列表
        for (HistoricTaskInstance task : taskInstanceList) {
            // 8. 基于任务对象, 得到流程实例 id, 查询流程实例对象
            HistoricProcessInstance instance = historyService.createHistoricProcessInstanceQuery()
                    .processInstanceId(task.getProcessInstanceId())
                    .singleResult();
            // 9. 基于流程实例对象, 得到业务标识, 基于业务标识查询审核记录对象
            CarPackageAudit audit = carPackageAuditService.getById(instance.getBusinessKey());

            // 10. 将审核记录对象的数据拷贝到 vo 中, 并补充相应字段(完成时间/任务名称/负责人)
            CarPackageAuditVO vo = new CarPackageAuditVO();
            BeanUtils.copyBeanProp(vo,audit);

            vo.setFinishedTime(task.getEndTime());
            vo.setTaskId(task.getId());
            vo.setTaskName(task.getName());
            // 11. 查询任务的创建人并设置到审核记录
            vo.setAuditorys(SecurityUtils.getLoginUser().getUser().getNickName());
            // 12. 将 vo 对象加入返回的集合中
            list.add(vo);
        }
        // 13. 返回分页数据
        tableDataInfo.setRows(list);
        return tableDataInfo;
    }

    @Override
    public List<HistoricActivity> selectHistoryList(String instanceId) {
        // 1. 基于流程实例id查询到历史任务(已完成)列表
        List<HistoricActivityInstance> taskInstanceList = historyService.createHistoricActivityInstanceQuery()
                .processInstanceId(instanceId)
                .activityType("userTask")
                .orderByHistoricActivityInstanceStartTime()
                .asc()
                .list();
        // 2. 遍历历史任务集合, 基于任务id查询批注信息
        List<HistoricActivity> list = new ArrayList<>(taskInstanceList.size());
        for (HistoricActivityInstance instance : taskInstanceList) {
            HistoricActivity historicActivity = new HistoricActivity();
            BeanUtils.copyBeanProp(historicActivity,instance);

            // 3. 将批注信息保存到对象, 最终返回数据
            List<Comment> comments = taskService.getTaskComments(instance.getTaskId());
            if (!CollectionUtils.isEmpty(comments)){
                historicActivity.setComment(comments.get(0).getFullMessage());
            }
            list.add(historicActivity);
        }
        return list;
    }
}
